package io.shallwe.scanner.manual;
import java.nio.ByteBuffer;
import java.nio.charset.Charset;

import org.apache.commons.lang3.StringUtils;
import org.tio.client.intf.ClientAioHandler;
import org.tio.core.ChannelContext;
import org.tio.core.TioConfig;
import org.tio.core.exception.AioDecodeException;
import org.tio.core.intf.Packet;

import com.jfinal.aop.Aop;
import com.jfinal.kit.LogKit;

import io.shallwe._admin.basedata.scanner.ScannerService;
import io.shallwe._admin.line.EnterScanService;
import io.shallwe._admin.line.ExitScanService;
import io.shallwe.common.model.Scanner;

/**
 *   手动扫描枪数据处理器
 * @author 王小伟
 * @date 2016-06-16 08:21:11
 */
public class ManualScannerHandler implements ClientAioHandler{
	
	 EnterScanService enterScanService=Aop.get(EnterScanService.class);
	 ExitScanService exitScanService=Aop.get(ExitScanService.class);
	 ScannerService scannerService=Aop.get(ScannerService.class);
	 
	/**
	 * 解码
	 */
	@Override
	public MessagePacket decode(ByteBuffer buffer, int limit, int position, int readableLength,
			ChannelContext channelContext) throws AioDecodeException {
		if(readableLength<3) {
			return null;
		}
		MessagePacket imPacket = new MessagePacket();
		byte[] body = new byte[readableLength];
		buffer.get(body);
		imPacket.setBody(body);
		return imPacket;
	}

	/**
	 * 编码
	 */
	@Override
	public ByteBuffer encode(Packet packet, TioConfig config, ChannelContext channelContext) {
		MessagePacket helloPacket = (MessagePacket) packet;
		byte[] body = helloPacket.getBody();
		ByteBuffer buffer = ByteBuffer.allocate(body.length);
		buffer.order(config.getByteOrder());
		if (body != null) {
			buffer.put(body);
		}
		return buffer;
	}

	/**
	 * 处理客户端收到的消息
	 */
	@Override
	public void handler(Packet packet, ChannelContext channelContext) throws Exception {
		String ip = channelContext.getServerNode().getIp();
		if(scannerService==null) {
			return;
		}
		Scanner scanner = scannerService.findByIp(ip);
		if(scanner==null) {
			return;
		}
		MessagePacket helloPacket = (MessagePacket) packet;
		byte[] body = helloPacket.getBody();
		if (body == null) {
			return;
		}
		String code=new String(body,Charset.forName("UTF8"));
		LogKit.error(String.format("收到手动扫描枪:%s的数据:%s", ip, code));
		code=StringUtils.remove(code, (char)0x20);
		code=StringUtils.remove(code, (char)0x0D);
		code=StringUtils.remove(code, (char)0x02);
		code=StringUtils.remove(code, (char)0x03);
		code=StringUtils.remove(code, (char)0x04);
		//扫描员工号登陆扫描枪
		if(StringUtils.startsWith(code, "U#")) {
			String employeeNumber = StringUtils.substringAfter(code, "U#");
			scannerService.bindAccountByIp(ip, employeeNumber);
			return;
		}
		//触发上线手动扫描
		if(scanner.isManualEnter()) {
			enterScanService.scan(code, ip);
			return;
		}
		
		//触发下线手动扫描
		if(scanner.isManualExit()) {
			exitScanService.scan(code,ip);
			return;
		}
		
	}

	@Override
	public Packet heartbeatPacket(ChannelContext arg0) {
		return null;
	}
}